package com.by.yz.activity.regitser;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.by.yz.App;
import com.by.yz.R;
import com.by.yz.Register.RegisterRESTFul;
import com.by.yz.activity.LoginActivity;
import com.by.yz.activity.MainActivity;
import com.by.yz.activity.base.BaseActivity;
import com.by.yz.chatuidemo.DemoHelper;
import com.by.yz.common.MFGT;
import com.by.yz.entity.Register;
import com.by.yz.loginUtil.AccountRESTFul;
import com.by.yz.loginUtil.LoginRESTFul;
import com.by.yz.util.ToJSonObject;
import com.hyphenate.EMCallBack;
import com.hyphenate.EMError;
import com.hyphenate.chat.EMClient;
import com.hyphenate.easeui.utils.EaseUserUtils;
import com.hyphenate.exceptions.HyphenateException;
import com.jzxiang.pickerview.data.Type;
import com.jzxiang.pickerview.listener.OnDateSetListener;

import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Date;


/**
 * Created by apple on 2016/10/4.
 */

public class RegisterInfoActivity extends BaseActivity implements OnDateSetListener {
    private EditText register_name;
    private EditText register_password;
    private TextView register_sex;
    private TextView register_birth;
    private Button finish;
    private  String nick,password,number,bir;
    private  boolean sex=true;
    private boolean progressShow;
    com.jzxiang.pickerview.TimePickerDialog mDialogYearMonthDay;//生日选择
    SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registerinfo);
        long hundredYears = 100L * 365 * 1000 * 60 * 60 * 24L;
        //日期选择
        mDialogYearMonthDay = new com.jzxiang.pickerview.TimePickerDialog.Builder()
                .setType(Type.YEAR_MONTH_DAY)
                .setTitleStringId("日期选择")
                .setThemeColor(getResources().getColor(R.color.colorPrimary))
                .setCallBack(this)
                .setMinMillseconds(System.currentTimeMillis()-hundredYears)
                .setMaxMillseconds(System.currentTimeMillis())
                .build();

        register_name = (EditText) findViewById(R.id.register_name);
        register_password = (EditText) findViewById(R.id.register_password);
        final AlertDialog.Builder builder = new AlertDialog.Builder(RegisterInfoActivity.this); //定义选择性别对话框
        register_sex = (TextView) findViewById(R.id.register_sex);
        register_sex.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final String[] strarr = {"男", "女"};
                builder.setItems(strarr, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface arg0, int arg1) {
                        int sex1 = 0;// 自动生成的方法存根
                        if (arg1 != 0) {//女
                            sex1 = 1;
                            sex = false;
                        }
                        register_sex.setText(strarr[sex1]);
                    }
                });
                builder.show();
            }
        });
        register_birth = (TextView) findViewById(R.id.register_birth);
        register_birth.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialogYearMonthDay.show(getSupportFragmentManager(), "year_month_day");
            }
        });
        //完成
        finish = (Button) findViewById(R.id.register_finish);
        finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                nick  = register_name.getText().toString();
                password = register_password.getText().toString();
                bir = register_birth.getText().toString();

                AccountRESTFul accountRequste = new AccountRESTFul();
                accountRequste.get( new AccountRESTFul.IhttpCb() {
                    @Override
                    public void ok(JSONObject response) {
                        if (nick.equals("")||  password.equals("")||  bir.equals("") || register_sex.equals("")) {
                            new MaterialDialog.Builder(RegisterInfoActivity.this)
                                    .content("信息未填写完全")
                                    .show();
                        }else if(password.length()<6){
                            new MaterialDialog.Builder(RegisterInfoActivity.this)
                                    .content("请输入不少于6位的密码")
                                    .show();
                        } else {
                            final Intent intent = getIntent();
                            number = intent.getStringExtra("number").toString();
                            Register register=new Register();
                            register.setNickname(nick);
                            register.setNumber(number);
                            register.setPassword(password);
                            register.setSex(sex);
                            register.setBirthday(bir);
                            register.setCreatedBy("creat");
                            register.setCreatedDate("2017-01-13T09:27:29.423Z");
                            register.setEmail("");
                            register.setFirstName("first");
                            register.setLangKey("zh-cn");
                            register.setLastModifiedBy("last");
                            register.setLastModifiedDate("2017-01-13T09:27:29.423Z");
                            register.setLastName("last");
                            register.setLogin("");
                            JSONObject data = ToJSonObject.beanToJSONObejct(register);
                            RegisterRESTFul registerRequest = new RegisterRESTFul();
                            registerRequest.postjs(RegisterInfoActivity.this, data, new RegisterRESTFul.ILoginCb() {
                                @Override
                                public void ok(String response) {
                                    final ProgressDialog pd = new ProgressDialog(RegisterInfoActivity.this);
                                    pd.setMessage(getResources().getString(R.string.Is_the_registered));
                                    pd.show();
                                    new Thread(new Runnable() {
                                        public void run() {
                                            try {
                                                // call method in SDK
                                                EMClient.getInstance().createAccount(number, password);
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        if (!RegisterInfoActivity.this.isFinishing())
                                                            pd.dismiss();
                                                        // save current user
                                                        DemoHelper.getInstance().setCurrentUserName(number);
                                                        Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registered_successfully), Toast.LENGTH_SHORT).show();
                                                        //intent.setClass(RegisterInfoActivity.this, LoginActivity.class);
                                                        //intent.putExtra("number",number);
                                                        login();
                                                        //startActivity(intent);
                                                    }
                                                });
                                            } catch (final HyphenateException e) {
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        if (!RegisterInfoActivity.this.isFinishing())
                                                            pd.dismiss();
                                                        int errorCode=e.getErrorCode();
                                                        if(errorCode== EMError.NETWORK_ERROR){
                                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.network_anomalies), Toast.LENGTH_SHORT).show();
                                                        }else if(errorCode == EMError.USER_ALREADY_EXIST){
                                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.User_already_exists), Toast.LENGTH_SHORT).show();
                                                        }else if(errorCode == EMError.USER_AUTHENTICATION_FAILED){
                                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.registration_failed_without_permission), Toast.LENGTH_SHORT).show();
                                                        }else if(errorCode == EMError.USER_ILLEGAL_ARGUMENT){
                                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.illegal_user_name),Toast.LENGTH_SHORT).show();
                                                        }else{
                                                            Toast.makeText(getApplicationContext(), getResources().getString(R.string.Registration_failed), Toast.LENGTH_SHORT).show();
                                                        }
                                                    }
                                                });
                                            }
                                        }
                                    }).start();
                                }
                                @Override
                                public void error(String error) {
                                    Log.e("RegisterInfoError", error);
                                    final MaterialDialog registerSuccess = new MaterialDialog.Builder(RegisterInfoActivity.this)
                                            .content("注册失败")
                                            .show();
                                    Handler handler = new Handler();
                                    handler.postDelayed(new Runnable() {
                                        public void run() {
                                            //execute the task
                                            registerSuccess.dismiss();//设置弹框消失
                                        }
                                    }, 1000);
                                }
                            });
                        }

                    }
                    @Override
                    public void error(String error) {
                        // 授权失败
                        Log.e("GG", "授权失败");
                    }
                });

            }
        });
    }

    @Override
    public void onDateSet(com.jzxiang.pickerview.TimePickerDialog timePickerDialog, long millseconds) {
        String text = getDateToString(millseconds);
        register_birth.setText(text);
    }

    public String getDateToString(long time) {
        Date d = new Date(time);
        return sf.format(d);
    }

    public void login() {
        LoginRESTFul loginRESTFul = new LoginRESTFul();
        loginRESTFul.login(password, number, new LoginRESTFul.ILoginCb() {
            @Override
            public void ok(String response) {
                AccountRESTFul account=new AccountRESTFul();//更新权限，得到一个真实的令牌
                account.get(new AccountRESTFul.IhttpCb() {
                    @Override
                    public void ok(JSONObject response) {

                                    /*更新Token*/
                        String[] UserData=new String[3];
                        UserData[0]=number;
                        UserData[1]=password;
                        //设置Cookie，进行账号登陆缓存
                        App.setCacheUser(RegisterInfoActivity.this,UserData);
                        //用户登录，写入用户缓存
                        App.cacheUserToken(RegisterInfoActivity.this);
                                    /*更新Token完毕*/
                       // Toast.makeText(getApplicationContext(), "登陆成功", Toast.LENGTH_SHORT).show();
                        Intent intent=new Intent();
                        intent.setClass(RegisterInfoActivity.this, RegisterInfoNextActivity.class);
                        intent.putExtra("number",number);
                        startActivity(intent);
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            public void run() {
                                MFGT.finish(RegisterInfoActivity.this);
                            }
                        },2000);
                    }

                    @Override
                    public void error(String error) {
                        Log.e("AccountRESTFul-2-Error",error);
                    }
                });
            }

            @Override
            public void error(String error) {
                Log.e("LoginRESTFul-Error", error);
                final MaterialDialog registerSuccess = new MaterialDialog.Builder(RegisterInfoActivity.this)
                        .content("登陆失败,请检查手机号码和密码是否正确")
                        .show();
                Handler handler = new Handler();
                handler.postDelayed(new Runnable() {
                    public void run() {
                        registerSuccess.dismiss();//设置弹框消失
                    }
                }, 1000);
            }
        });
    }
}
